package com.example.controller;

import cn.hutool.crypto.digest.BCrypt;
import com.example.common.Result;
import com.example.entity.*;
import com.example.exception.CustomException;
import com.example.service.AdminService;
import com.example.service.StudentInfoService;
import com.example.service.SysUserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 管理员前端操作接口
 **/
@RestController
@RequestMapping("/sysUser")
public class SysUserController {

    private static final Logger log = LoggerFactory.getLogger(SysUserController.class);

    @Resource
    private SysUserService sysUserService;

    @Resource
    private StudentInfoService studentInfoService;

    /**
     * 新增
     */
    /**
     * 新增用户（包含学生信息）
     */
    @PostMapping("/add")
    public Result add(@RequestBody UserStudentDTO userDTO) {
        try {
            // 转换为SysUser对象
            SysUser sysUser = new SysUser();
            BeanUtils.copyProperties(userDTO, sysUser);

            // 如果是学生类型，同时保存学生信息
            if (userDTO.getUserType() == 5 && userDTO.getStudentInfo() != null) {
                sysUserService.addWithStudentInfo(sysUser, userDTO.getStudentInfo());
            } else if ((userDTO.getUserType() == 1 || userDTO.getUserType() == 2) && userDTO.getMemberInfo() != null) {
                sysUserService.addWithMemberInfo(sysUser, userDTO.getMemberInfo());
            } else {
                sysUserService.add(sysUser);
            }
            return Result.success();
        } catch (Exception e) {
            log.error("添加用户失败", e);
            return Result.error("添加用户失败");
        }
    }

    /**
     * 删除用户（同时删除关联的学生信息）
     */
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable Integer id) {
        sysUserService.deleteWithStudentInfo(id);
        return Result.success();
    }
    /**
     * 批量删除
     */
    @DeleteMapping("/delete/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        sysUserService.deleteBatch(ids);
        return Result.success();
    }


    /**
     * 修改用户（包含学生信息）
     */
    @PutMapping("/update")
    public Result updateById(@RequestBody UserStudentDTO userDTO) {
        try {
            SysUser sysUser = new SysUser();
            BeanUtils.copyProperties(userDTO, sysUser);

            if (userDTO.getUserType() == 5 && userDTO.getStudentInfo() != null) {
                sysUserService.updateWithStudentInfo(sysUser, userDTO.getStudentInfo());
            } else if ((userDTO.getUserType() == 1 || userDTO.getUserType() == 2) && userDTO.getMemberInfo() != null) {
                sysUserService.updateWithMemberInfo(sysUser, userDTO.getMemberInfo());
            } else {
                sysUserService.updateById(sysUser);
            }
            return Result.success();
        } catch (Exception e) {
            log.error("更新用户失败", e);
            return Result.error("更新用户失败");
        }
    }



    /**
     * 根据ID查询（包含学生信息）
     */
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Long id) {
        Map<String, Object> result = sysUserService.selectWithStudentInfo(id);
        return Result.success(result);
    }

    /**
     * 查询所有
     */
    @GetMapping("/selectAll")
    public Result selectAll(SysUser sysUser) {
        List<SysUser> list = sysUserService.selectAll(sysUser);
        return Result.success(list);
    }

    /**
     * 分页查询
     */
    @GetMapping("/selectPage")
    public Result selectPage(SysUser sysUser,
                             @RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<SysUser> page = sysUserService.selectPage(sysUser, pageNum, pageSize);
        return Result.success(page);
    }


    /**
     * 注册
     */
    @PostMapping("/register")
    public Result register(@RequestBody SysUser user) {
        sysUserService.register(user);
        return Result.success();
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginDTO loginDTO) {
        SysUser userLogin = sysUserService.login(loginDTO);
        return Result.success(userLogin);
    }

    /**
     * 修改密码
     */
    @PutMapping("/updatePassword")
    public Result updatePassword(@RequestBody PasswordUpdateDTO passwordDTO) {
        int updated = sysUserService.updatePassword(passwordDTO);
        if (updated > 0) {
            return Result.success("密码修改成功");
        } else {
            return Result.error("密码修改失败");
        }
    }
    /**
     * 搜索用户（支持教师和学生）
     */
    @GetMapping("/search")
    public Result search(@RequestParam String realName,
                         @RequestParam(required = false) String userTypes) {
        try {
            if (StringUtils.isBlank(realName)) {
                return Result.error("搜索关键词不能为空");
            }

            // 将逗号分隔的字符串转换为整数列表
            List<Integer> userTypeList;
            if (StringUtils.isBlank(userTypes)) {
                userTypeList = List.of(1, 2, 4, 5); // 默认搜索教师和学生
            } else {
                userTypeList = Arrays.stream(userTypes.split(","))
                        .map(Integer::parseInt)
                        .collect(Collectors.toList());
            }

            SysUser query = new SysUser();
            query.setRealName(realName);
            List<SysUser> users = sysUserService.searchUsers(query, userTypeList);

            return Result.success(users);
        } catch (Exception e) {
            log.error("搜索用户失败", e);
            return Result.error("搜索用户失败");
        }
    }

    /**
     * 获取用户详情（包含学生信息）
     */
    @GetMapping("/{id}")
    public Result getUserDetail(@PathVariable Long id) {
        try {
            Map<String, Object> userDetail = sysUserService.selectWithStudentInfo(id);
            return Result.success(userDetail);
        } catch (Exception e) {
            log.error("获取用户详情失败", e);
            return Result.error("获取用户详情失败");
        }
    }
}